﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.Serialization.Json;
using System.IO;

namespace Redboil.Bfp.Core {
    /// <summary>
    /// 
    /// </summary>
    public class JsonHelper {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        //public static String Serialize<T>(T t) {
        //    var serializer = new DataContractJsonSerializer(typeof(T));
        //    using(var stream = new MemoryStream()) {
        //        serializer.WriteObject(stream, t);
        //        return Encoding.UTF8.GetString(stream.ToArray());
        //    }
        //}

        public static String Serialize<T>(IList<T> list) {
            var serializer = new DataContractJsonSerializer(typeof(IList<T>));
            using(var stream = new MemoryStream()) {
                serializer.WriteObject(stream, list);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        //public static T Deserialize<T>(String result) {
        //    var serializer = new DataContractJsonSerializer(typeof(T));
        //    var bytesResult = Encoding.UTF8.GetBytes(result);
        //    using(var stream = new MemoryStream(bytesResult)) {
        //        return (T)serializer.ReadObject(stream);
        //    }
        //}

        public static IList<T> Deserialize<T>(String result) {
            var serializer = new DataContractJsonSerializer(typeof(IList<T>));
            var bytesResult = Encoding.UTF8.GetBytes(result);
            using(var stream = new MemoryStream(bytesResult)) {
                return serializer.ReadObject(stream) as IList<T>;
            }
        }

        //ASP.NET中的JSON序列化和反序列化还可以使用JavaScriptSerializer，在 System.Web.Script.Serializatioin命名空间下，需引用System.Web.Extensions.dll
        //JavaScriptSerializer jserializer = new JavaScriptSerializer();
        //2 
        //3 User user = jserializer.Deserialize<User>("{\"UserName\":\"user\",\"TrueName\":\"wange\",\"Address\":{\"City\":\"beijing\",\"Country\":\"China\"},\"AddressList\":[{\"City\":\"ShangHai\",\"Country\":\"China\"},{\"City\":\"ShiJiaZhuang\",\"Country\":\"China\"}]}");//将Json字符串转换为实体类

        //            using(Stream responseStream = ea.Result 
        //                response.GetResponseStream())
        //{
        //}

    }
}
